package cn.com.jonpad.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author Jon Chan
 * @date 2019/5/12 23:02
 */
@RestController
@Slf4j
public class TestController {
    @GetMapping("1")
    private String mono1(){
        log.info("开始1");
        String s = getString("get1");
        log.info("结束1");
        return s;
    }
    @GetMapping("2")
    private Mono<String> mono2(){
        log.info("开始2");
        Mono<String> result = Mono.fromSupplier(()->getString("get1"));
        log.info("结束2");
        return result;
    }
    @GetMapping(value = "3", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    private Flux<String> flux1(){
        log.info("开始3");
        Flux<String> result = Flux.fromStream(IntStream.range(1,5).mapToObj(i->{
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
            }
            return "flux data: "+ i;
        }));
        log.info("结束3");
        return result;
    }

    private String getString(String x) {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
        }
        return "get String : " + x;
    }
}
